package com.example.black.myapplication.mynet;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

public class JsonRequest<T> implements CallBackListener {
    private static final String TAG = Request.class.getSimpleName();
    private  Gson gson;
    private IJSONResponseCallBack<T> callBack;
    private Class<T> responseClass;
    private static final int SUCCESS = 983;
    private static final int FAILURE = 610;
    private Handler handler = new Handler(Looper.getMainLooper()){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == FAILURE){
                callBack.onFailure((Throwable) msg.obj);
                return;
            }
            T data = (T) msg.obj;
            callBack.onSuccess(data);
        }
    };
    public JsonRequest(Class<T> responseClass,IJSONResponseCallBack<T> callBack){
        gson = new GsonBuilder().create();
        this.responseClass = responseClass;
        this.callBack = callBack;
    }
    @Override
    public void onSuccess(InputStream inputStream) {
        Log.e(TAG, "onSuccess: ");
        Message message = Message.obtain();
        try {
            byte[] data=new byte[1024];
            StringBuffer sb1=new StringBuffer();
            int length=0;
            while ((length=inputStream.read(data))!=-1){
                String s=new String(data, Charset.forName("utf-8"));
                sb1.append(s);
            }
           String originalJson =sb1.toString();
            message.what = SUCCESS;
            if (responseClass == String.class){
                message.obj = originalJson;
            }else {
                message.obj = gson.fromJson(originalJson,responseClass );

            }
            handler.sendMessage(message);
        }catch (IOException e){
            Log.e(TAG, "onSuccess: error",e);
            sendErrorMessage(e);
        }

    }

    private void sendErrorMessage( Throwable e) {
        Message message = Message.obtain();
        message.what = FAILURE;
        message.obj = e;
        handler.sendMessage(message);
    }

    @Override
    public void onFailure(Throwable throwable) {
       sendErrorMessage(throwable);
    }

}
